package com.yups.web;

import com.yups.dao.EmpDao;
import com.yups.model.Emp;
import com.yups.utils.MailUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Random;

/**
 * @author 于鹏生
 */
@WebServlet(urlPatterns = "/FindPasswordAction")
public class FindPasswordAction extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String mob = request.getParameter("mob");
        String email = request.getParameter("email");
        Emp emp = empDao.get(mob, email);
        if(emp==null){
            forward(request,response,"msg","您的输入不正确",
                    "WEB-INF/jsp/findPassword.jsp");
            return;
        }
        //给邮箱发东西
        HttpSession session = request.getSession();
        String tocken=String.valueOf(new Random().nextInt(10000));
        session.setAttribute(tocken,emp);
        String context="您可以通过以下地址," +
                "<a href=http://localhost:9090/BookSystem04/FindAction?act=updatePassword&a="+
                session.getId()+"&b="+tocken+">修改</a>您的密码"
                +"http://localhost:9090/BookSystem04/FindAction?act=updatePassword&a="+
                session.getId()+"&b="+tocken;
        System.out.println(context);
        session.setAttribute("id",session.getId());
        if(MailUtils.sendMail(email,context,"用户" +mob+
                "找回密码")){
            session.setMaxInactiveInterval(30*60);
            forward(request,response,"msg","您的密码找回链接已经发送到您的邮箱，请在30分钟内进行修改操作",
                    "WEB-INF/jsp/findPassword.jsp");
        }else{
            forward(request,response,"msg","邮件发送失败，请稍后再试。",
                    "WEB-INF/jsp/findPassword.jsp");
        }



    }

    private EmpDao empDao=new EmpDao();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.setAttribute("id",session.getId());
        System.out.println(session.getAttribute("id"));
        System.out.println(response.encodeRedirectURL("FindPasswordAction"));
        forward(request,response,"WEB-INF/jsp/findPassword.jsp");
    }

    private void forward(HttpServletRequest request, HttpServletResponse response, String url) throws ServletException, IOException {
        request.getRequestDispatcher(url).forward(request, response);
    }
    private void forward(HttpServletRequest request, HttpServletResponse response, String key,Object value, String url) throws ServletException, IOException {
        request.setAttribute(key, value);
        request.getRequestDispatcher(url).forward(request, response);
    }

}
